package com.parking.renters.controller;


import cn.hutool.core.bean.BeanUtil;
import com.parking.common.core.model.PageInfo;
import com.parking.common.core.model.Result;
import com.parking.common.core.util.JwtUtil;
import com.parking.common.web.util.FileUtil;
import com.parking.common.web.util.OssUtil;
import com.parking.common.web.util.RedisUtil;
import com.parking.renters.entity.RentersInfo;
import com.parking.renters.exception.RentersException;
import com.parking.renters.exceptionCode.RentersExceptionCode;
import com.parking.renters.model.stallCall.dto.RentersInfoDto;
import com.parking.renters.model.stallCall.dto.SelectRentersInfoByIdDTO;
import com.parking.renters.model.stallCall.dto.SelectRentersInfoDTO;
import com.parking.renters.model.stallCall.form.AuthenticationNameForm;
import com.parking.renters.model.stallCall.form.PerfectCertifiedForm;
import com.parking.renters.model.stallCall.form.SelectRentersForm;
import com.parking.renters.model.stallCall.form.UpdateRentersImgForm;
import com.parking.renters.service.RentersInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 彭于晏
 * @since 2023年11月29日
 */
@RestController
@RequestMapping("/rentersInfo")
@Api(tags = "出租客信息")
public class RentersInfoController {


    @Autowired
    private RentersInfoService rentersInfoService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private OssUtil ossUtil;

    /**
     *车位模块的调用
     *  selectRentersInfo：根据出租客id查询出租客信息
     * @param rentersId:出租客账号id
     * @return SelectRentersInfoDTO：出租客信息对象
     */
    @GetMapping("/selectRentersInfo/{rentersId}")
    @ApiOperation("根据出租客id查询出租客信息(车位模块的调用)")
    public Result<SelectRentersInfoDTO> selectRentersInfo (@PathVariable("rentersId") Integer rentersId)throws Exception{
        if (rentersId==null) {
            throw new RentersException(RentersExceptionCode.PARAM_NOT_EXISTS);
        }
        RentersInfo rentersInfo = rentersInfoService.getById(rentersId);
        if (rentersInfo==null) {
            throw new RentersException(RentersExceptionCode.RENTERS_INFO_NOT_EXISTS);//出租客信息不存在
        }
        SelectRentersInfoDTO dto = BeanUtil.toBean(rentersInfo,SelectRentersInfoDTO.class);
        return Result.getResult(SelectRentersInfoDTO.class).setMessage("查询成功").setData(dto);
    }
    /**
     * 根据ID查询出租客信息
     * 参数: 出租客信息Id rentersInfoId
     * 返回: 出租客姓名 rentersInfoName
     *      出租客年龄 rentersInfoAge
     *      出租客电话 rentersInfoTel
     *      出租客头像 rentersInfoImg
     * 方法: 1.判断rentersInfoId是否存在对应的出租客信息 若不存在则抛异常
     *      2.判断对应的出租客是否实名 若不是则抛异常
     *      3.将出租客信息放入Dto返回
     * */
    @GetMapping("/selectRentersById")
    @ApiOperation("根据ID查询出租客信息(订单模块调用)")
    Result<RentersInfoDto> selectRentersInfoById(@RequestParam("rentersInfoId") Integer rentersInfoId){
        RentersInfoDto dto = rentersInfoService.selectRentersInfoById(rentersInfoId);
        return Result.getResult().setMessage("查询成功").setCode(200).setData(dto);
    }

    /***
     * 出租客实名认证
     * @param form
     * @param authorization
     * @return
     * @throws Exception
     */
    @PostMapping("/att.renters")
    @ApiOperation("出租客实名认证")
   public Result AuthenticationName(@RequestBody @Valid AuthenticationNameForm form,@RequestHeader("authorization")String authorization)throws Exception{
        String refreshToken = redisUtil.get(authorization);
        Integer rentersId = JwtUtil.getRentersId(refreshToken);
        Boolean bo=rentersInfoService.AuthenticationName(form,rentersId);
        if (bo) {
            return Result.getResult().setCode(200).setMessage("用户实名认证成功").setFlag(true);
        }else {
            return Result.getResult().setCode(200).setMessage("用户实名认证失败").setFlag(false);
        }
   }
   ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    @GetMapping("/selectRentersRealName")
    @ApiOperation("判断出租客是否实名")
    public Result<RentersInfoDto> selectRentersRealName(@RequestParam("rentersInfoId") Integer rentersInfoId){
        RentersInfoDto dto = rentersInfoService.selectRentersRealName(rentersInfoId);
        return Result.getResult().setMessage("出租客已经实名").setData(dto).setCode(200);
    }
    /***
     * 平台根据条件查询出租客信息
     * @param form  condition 条件 pageNum 页数  pageSize 总条数
     * @return pageInfo
     */
   @PostMapping("/selectRenters.platform")
   @ApiOperation("平台查询出租客信息")
   public Result selectRentersInfo(@RequestBody SelectRentersForm form){
       PageInfo pageInfo = rentersInfoService.selectRentersInfo(form);
       return Result.getResult().setCode(200).setMessage("查询成功").setData(pageInfo);
   }

    /***
     * 物业根据条件查询出租客信息
     * @param form  condition 条件 pageNum 页数  pageSize 总条数
     * @return pageInfo
     */
   @PostMapping("/selectRenter.certified")
   @ApiOperation("物业查询出租客信息")
    public Result selectRenters(@RequestBody SelectRentersForm form){
       PageInfo pageInfo = rentersInfoService.selectRenters(form);
       return Result.getResult().setMessage("查询成功").setCode(200).setData(pageInfo);
    }

    /***
     * 出租客修改联系方式
     * @param rentersInfoTel 联系方式
     * @param authorization
     * @return
     * @throws Exception
     */
    @PostMapping("/update")
    @ApiOperation("修改出租客信息")
    public Result updateRenters(String rentersInfoTel,@RequestHeader("Authorization")String authorization)throws Exception{
        Integer rentersId = JwtUtil.getRentersId(authorization);
        rentersInfoService.updateRenters(rentersId,rentersInfoTel);
        return Result.getResult().setMessage("修改成功").setCode(200);
    }
    /**
     * 车位模块调用
     * rentersInfoCallById：调用出租客信息
     * @param rentersInfoId 出租客信息id
     * @return SelectRentersInfoDTO：出租客信息返回对象
     * @throws Exception
     */
    @GetMapping("/selectRenters/{rentersInfoId}")
    @ApiOperation("(车位模块调用)根据id查询出租客信息")
    public Result<SelectRentersInfoByIdDTO> rentersInfoCallById (@PathVariable("rentersInfoId") Integer rentersInfoId){
        SelectRentersInfoByIdDTO dto = rentersInfoService.rentersInfoCallById(rentersInfoId);
        return Result.getResult(SelectRentersInfoByIdDTO.class).setMessage("查询成功").setCode(200).setData(dto);
    }
///////////////////////////////////////////////////////////////////////////////////////*///////////////////////////////////
    @ApiOperation("上传出租客头像")
    @PostMapping("/upload.renters")
    public Result upLoad(MultipartFile image, @RequestHeader("authorization")String authorization) throws Exception {
        InputStream stream = image.getInputStream();
        byte[] header=new byte[8];//解析字节码
        stream.read(header,0,8);//字节流读取文件
        if (!(FileUtil.isJpg(header)||FileUtil.isPng(header))){
          //真=》假=》真（抛异常）
          throw new RentersException(RentersExceptionCode.RENTERS_DILE_NO);
        }
        //去掉uuid的横线
        String prefix = UUID.randomUUID().toString().replaceAll("-", "");
        //随机字符后缀文件格式
        String name = prefix + "." + (FileUtil.isJpg(header) ? "jpg" : "png");
        //调用上传oss的方法，获取oss的地址
        String path = ossUtil.uploadFile(image.getInputStream(), name);
        String refreshToken = redisUtil.get(authorization);
        Integer userId = JwtUtil.getRentersId(refreshToken);
        rentersInfoService.upLoad(path,userId);
        return Result.getResult().setMessage("上传头像成功").setCode(200).setData(path);
    }
    @PostMapping("/upBookImage.renters")
    @ApiOperation("修改头像")
    public Result upUserInfoImg(MultipartFile image,@RequestHeader("authorization") String authorization) throws Exception {
        InputStream stream = image.getInputStream();
        byte[] header=new byte[8];//解析字节码
        stream.read(header,0,8);//字节流读取文件
        if (!(FileUtil.isJpg(header)||FileUtil.isPng(header))){
            //真=》假=》真（抛异常）
            throw new RentersException(RentersExceptionCode.RENTERS_DILE_NO);
        }
        //去掉uuid的横线
        String prefix = UUID.randomUUID().toString().replaceAll("-", "");
        //随机字符后缀文件格式
        String name = prefix + "." + (FileUtil.isJpg(header) ? "jpg" : "png");
        UpdateRentersImgForm form = new UpdateRentersImgForm();
        form.setFileName(name);
        form.setImage(image);
        String refreshToken = redisUtil.get(authorization);
        Integer rentersId = JwtUtil.getRentersId(refreshToken);
        form.setRentersInfoId(rentersId);
        rentersInfoService.updateRentersImg(form);
        return Result.getResult().setMessage("修改营业执照成功").setCode(200);
    }

    /***
     * 完善信息成功
     *
     * @param form
     * @param
     * @return
     */
    @PostMapping("/perfectCertifiedInfo")
    @ApiOperation("完善出租客物业信息")
    public Result  perfectCertifiedInfo(PerfectCertifiedForm form,@RequestHeader("authorization") String authorization) throws Exception {
        String refreshToken = redisUtil.get(authorization);
        Integer rentersId = JwtUtil.getRentersId(refreshToken);
        rentersInfoService.perfectCertifiedInfo(form,rentersId);
        return Result.getResult().setCode(200).setMessage("完善信息成功");
    }

}

